package org.lw.server.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.lw.server.common.RespBean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;

/**
 * 验证码控制器
 *
 * @author looveh
 * @since 2022/1/22 16:39
 **/
@RestController
@Api(value = "验证码控制器", tags = "验证码控制器tag")
public class CaptchaController {

    @Resource
    private DefaultKaptcha defaultKaptcha;

    @ApiOperation(value = "验证码", notes = "验证码notes", produces = "image/jpeg")
    @GetMapping("/captcha")
    public void captcha(HttpServletRequest request, HttpServletResponse response) {
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");

        // ------------生成验证码开始-------------
        String text = defaultKaptcha.createText();
        System.out.println("验证码内容：" + text);
        // 将验证码放入session
        request.getSession().setAttribute("captcha", text);
        // 生成验证码图片
        BufferedImage image = defaultKaptcha.createImage(text);
        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            ImageIO.write(image, "jpg", outputStream);
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != outputStream) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        // ------------生成验证码开始-------------

    }
}
